package com.osgix.common.orm.ibatis;

import java.lang.reflect.Field;

import javax.persistence.Id;

import org.apache.commons.lang.ClassUtils;
import org.nutz.lang.Mirror;
import org.nutz.lang.Strings;

/**
 * 实体类抽象基类
 */
public abstract class BaseEntity implements java.io.Serializable {

	private Mirror m = Mirror.me(this);

	protected static final String DATE_FORMAT = "yyyy-MM-dd";

	protected static final String TIME_FORMAT = "HH:mm:ss";

	protected static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

	protected static final String TIMESTAMP_FORMAT = "yyyy-MM-dd HH:mm:ss.S";

	/**
	 * 得到主键字段(首先查找@Id标识的字段,再查找"类名+Id"字段)
	 */
	public Field getPkField() {
		Field pkField = Mirror.findField(this.getClass(), Id.class);
		if (pkField == null) {
			try {
				String pkFieldName = Strings.lowerFirst(ClassUtils.getShortClassName(this.getClass()) + "Id");
				pkField = m.getField(pkFieldName);
			} catch (NoSuchFieldException e) {
				e.printStackTrace();
			}
		}
		return pkField;
	}

	/**
	 * 得到主键字段的值
	 */
	public Object getPkValue() {
		return m.getValue(this, getPkField());
	}

}
